package com.cyq.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyq.blog.entity.Blog;
import com.cyq.blog.entity.Category;
import com.cyq.blog.service.BlogService;
import com.cyq.blog.service.CategoryService;
import com.cyq.blog.util.MybatisPlusUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author chenyeqing
 * @Date 2021/5/17 21:23
 */
@Slf4j
@Controller
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BlogController blogController;

    @Autowired
    private BlogService blogService;
    /**
     * 查询所有 没被删除 的分类
     * @return
     */
    @ResponseBody
    @PostMapping("/admin/addCategory")
    public boolean listCategory(Category category) {
        log.info("添加分类=>" + category);
        category.setCategoryIcon(StringUtils.hasText(category.getCategoryIcon()) ? category.getCategoryIcon() : null);
        boolean save = categoryService.save(category);
        return save;
    }

    /**
     * 跳转到 分类页面
     * @return
     */
    @GetMapping("/toCategoryPage")
    public String toCategoryPage(Model model, @RequestParam(value = "categoryId", required = false) String categoryId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper();
        List<Category> categories = categoryService.list(queryWrapper);
        model.addAttribute("categories", categories);


        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper();
        if (StringUtils.hasText(categoryId)) {
            blogQueryWrapper.eq("blog_category_id", categoryId);
        }
        queryWrapper.eq("blog_status", 1);
        List<Blog> blogs = blogService.list(blogQueryWrapper);
        model.addAttribute("blogs", blogs);

        // 右侧排行榜
        blogController.blogViews(model);

        return "/blog/categoryPage";
    }


}
